# -*- coding: utf-8 -*-

from odoo import models, fields, api


class CpqCostLine(models.Model):
    _name = 'cpq.cost.line'
    _description = '成本明细'
    _order = 'sequence, id'
    
    # ============ 基础信息 ============
    cost_model_id = fields.Many2one(
        'cpq.cost.model',
        string='成本模型',
        required=True,
        ondelete='cascade'
    )
    
    sequence = fields.Integer(
        string='序号',
        default=10
    )
    
    # ============ 成本类型 ============
    cost_type = fields.Selection([
        ('material', '原材料'),
        ('tooling', '工装模具'),
        ('process', '加工工序'),
        ('labor', '人工'),
        ('overhead', '间接费用'),
        ('quality', '质量检测'),
        ('packaging', '包装物流'),
        ('other', '其他')
    ], string='成本类型', required=True, default='material')
    
    # ============ 成本项 ============
    name = fields.Char(
        string='成本项名称',
        required=True
    )
    
    description = fields.Text(
        string='说明'
    )
    
    product_id = fields.Many2one(
        'product.product',
        string='物料',
        help='如果是物料成本，关联物料'
    )
    
    # ============ 成本计算 ============
    unit_cost = fields.Monetary(
        string='单位成本',
        currency_field='currency_id',
        required=True
    )
    
    quantity = fields.Float(
        string='数量',
        default=1.0,
        required=True,
        digits='Product Unit of Measure'
    )
    
    uom_id = fields.Many2one(
        'uom.uom',
        string='单位',
        default=lambda self: self.env.ref('uom.product_uom_unit')
    )
    
    waste_rate = fields.Float(
        string='损耗率(%)',
        default=0.0,
        help='废品率、水口料等损耗'
    )
    
    subtotal = fields.Monetary(
        string='小计',
        compute='_compute_subtotal',
        store=True,
        currency_field='currency_id'
    )
    
    currency_id = fields.Many2one(
        'res.currency',
        related='cost_model_id.currency_id',
        string='货币'
    )
    
    # ============ 工装摊销特殊字段 ============
    is_amortized = fields.Boolean(
        string='需要摊销',
        default=False,
        help='工装模具等固定资产需要摊销'
    )
    
    total_tooling_cost = fields.Monetary(
        string='工装总成本',
        currency_field='currency_id',
        help='模具、夹具等固定资产的总投资'
    )
    
    amortization_quantity = fields.Float(
        string='摊销基数(总产量)',
        help='用于计算单件摊销成本的总产量'
    )
    
    # ============ 工序相关 ============
    operation_id = fields.Many2one(
        'mrp.routing.workcenter',
        string='工序',
        help='制造工序'
    )
    
    cycle_time = fields.Float(
        string='周期时间(秒)',
        help='工序的标准周期时间'
    )
    
    machine_hour_rate = fields.Monetary(
        string='机台小时费率',
        currency_field='currency_id'
    )
    
    labor_hour_rate = fields.Monetary(
        string='人工小时费率',
        currency_field='currency_id'
    )
    
    # ============ 供应商相关 ============
    supplier_id = fields.Many2one(
        'res.partner',
        string='供应商',
        domain=[('supplier_rank', '>', 0)]
    )
    
    # ============ 备注 ============
    notes = fields.Text(
        string='备注'
    )
    
    # ============ 计算字段 ============
    @api.depends('unit_cost', 'quantity', 'waste_rate', 'is_amortized', 
                 'total_tooling_cost', 'amortization_quantity', 'cycle_time',
                 'machine_hour_rate', 'labor_hour_rate')
    def _compute_subtotal(self):
        """计算小计"""
        for line in self:
            if line.is_amortized and line.amortization_quantity > 0:
                # 工装摊销: 总成本 / 摊销数量
                line.subtotal = line.total_tooling_cost / line.amortization_quantity
            elif line.cost_type == 'process' and line.cycle_time > 0:
                # 加工成本: (机台费率 + 人工费率) × 周期时间(小时)
                cycle_hours = line.cycle_time / 3600  # 秒转小时
                line.subtotal = (line.machine_hour_rate + line.labor_hour_rate) * cycle_hours
            else:
                # 普通成本: 单价 × 数量 × (1 + 损耗率)
                effective_qty = line.quantity * (1 + line.waste_rate / 100)
                line.subtotal = line.unit_cost * effective_qty
    
    # ============ Onchange ============
    @api.onchange('product_id')
    def _onchange_product_id(self):
        """当选择物料时，自动填充成本"""
        if self.product_id:
            self.name = self.product_id.name
            self.unit_cost = self.product_id.standard_price
            self.uom_id = self.product_id.uom_id
            
            # 获取第一个供应商
            if self.product_id.seller_ids:
                self.supplier_id = self.product_id.seller_ids[0].partner_id
                # 使用供应商价格
                self.unit_cost = self.product_id.seller_ids[0].price
    
    @api.onchange('cost_type')
    def _onchange_cost_type(self):
        """根据成本类型设置默认值"""
        if self.cost_type == 'tooling':
            self.is_amortized = True
            if self.cost_model_id:
                self.amortization_quantity = self.cost_model_id.estimated_quantity

